var MaterialBalance = function () {
  var template = /* html */ `
    <div class="material-balance" v-loading.fullscreen.lock="loading">
      <search-btn-view immediate btn-text="应付账款查询" @before-open="resetSearch" @search="searchData">
        <template slot="append">
          <el-button size="medium" type="primary" @click="lookStat">查看汇总</el-button>
          <el-button size="medium" type="primary" @click="exportExcel">导出Excel</el-button>
          <el-button v-if="selectWarehouseList.length>0" size="medium" type="primary" @click="paymentMoneys">批量付款</el-button>
        </template>
        <template slot="right">
          <table-col-show-select v-if="tableHideColumnKey!==null" :table-name="tableName" :current-column-name="currentColumnName"
            :hide-column.sync="tableHideColumnKey">
          </table-col-show-select>
        </template>

        <div slot="search-content">
          <material-search-form :search="search" :dropdown-option="dropdownOption"></material-search-form>
        </div>
      </search-btn-view>
      <div class="material-balance-stat" v-if="statData!==null&&warehouseList.length>0">
        <span style="margin-right:5px">
          <label>应付总额：</label>
          <span style="color:green">{{statData.totalMoney}}</span>
          <label>未付总额：</label>
          <span style="color:green;">{{statData.nonReceiptPaymentPrice}}</span>
          <label>已付总额：</label>
          <span style="color:green">{{statData.receiptPaymentPrice}}</span>
          <label>本月应付：</label>
          <span style="color:green;">{{statData.monthSum}}</span>
          <label>本月未付：</label>
          <span style="color:green;">{{statData.monthMoney}}</span>
        </span>
        <span>提示：若未付款结算，结算金额为采购金额;若有付款，结算金额为实际付款金额</span>
      </div>
      <div class="material-balance-table-div">
        <el-table fit stripe border ref="inMaterialBalance" :data="warehouseList" style="width: 100%" height="parent" @row-click="lookPaymentRcord"
          :hide-column-keys="getTableHideColumns()" @selection-change="selectionChange">
          <el-table-column :resizable="false" type="selection"  column-key="selection" key="selection "width="40px" fixed="left" align="center"
            :selectable="checkSelectable"></el-table-column>
          <el-table-column :resizable="false" label="操作" column-key="handle" key="handle" :width="handleWidth" fixed="left" align="center">
            <template slot-scope="scope">
              <div v-if="scope.row.isBalance==='0'">
                <el-button type="primary" size="mini" @click.stop="balanceOrder(scope.row)">结算</el-button>
                <el-button style="margin-left:0" type="primary" size="mini" @click.stop="paymentMoney(scope.row)">付款</el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" column-key="type" label="入库类型" key="type" width="120px" align="center">
            <template slot-scope="scope">
              <span>{{i18n.getMsg('financeMgr.type.'+scope.row.type)}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="purchaseId" key="purchaseId" label="采购单号" min-width="140px" header-align="center">
          </el-table-column>
          <el-table-column prop="orderId" key="orderId" label="订单编号" min-width="140px" header-align="center">
          </el-table-column>
          <el-table-column prop="factoryNo" key="factoryNo" label="工厂型号" min-width="120px" header-align="center">
          </el-table-column>
          <el-table-column prop="coustomId" key="coustomId" label="客户型号" min-width="120px" header-align="center">
          </el-table-column>
          <el-table-column prop="providerName" key="providerName" label="供应商" min-width="120px" header-align="center">
          </el-table-column>
          <el-table-column prop="materialName" key="materialName" label="物料名称" min-width="120px" header-align="center">
          </el-table-column>
          <el-table-column prop="materialType" key="materialType" label="物料类型" min-width="120px" header-align="center">
          </el-table-column>
          <el-table-column prop="model" key="model" label="规格型号" min-width="120px" header-align="center">
          </el-table-column>
          <el-table-column prop="color" key="color" label="编号" min-width="120px" header-align="center">
          </el-table-column>
          <el-table-column prop="colorDescription" key="colorDescription" label="描述" min-width="120px" header-align="center">
          </el-table-column>
          <el-table-column prop="defaultWarehouse" key="defaultWarehouse" label="默认仓位" min-width="100px" align="center">
          </el-table-column>
          <el-table-column prop="materialDeptName" key="materialDeptName" label="物料部门" min-width="120px" align="center">
          </el-table-column>
          <el-table-column prop="inCountUnit" key="inCountUnit" label="入库单位" min-width="100px" align="center"></el-table-column>
          <el-table-column prop="inCountPrice" key="inCountPrice" label="入库单价" min-width="100px" align="center"></el-table-column>
          <el-table-column prop="unitPrice" key="unitPrice" label="采购单价" min-width="100px" align="center"></el-table-column>
          <el-table-column prop="count" key="count" label="数量" min-width="100px" align="center"></el-table-column>
          <el-table-column prop="totalPrice" key="totalPrice" label="入库金额" min-width="100px" align="center"></el-table-column>
          <el-table-column prop="receiptPaymentPrice" key="receiptPaymentPrice" label="已付金额" min-width="100px" align="center">
          </el-table-column>
          <el-table-column prop="addReducePrice" key="addReducePrice" label="增减金额" min-width="100px" align="center">
          </el-table-column>
          <el-table-column prop="isTax" key="isTax" label="是否含税" min-width="100px" align="center">
            <template slot-scope="scope">
              <span>{{i18n.getMsg('common.isTax.'+scope.row.isTax)}}</span>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" column-key="isBalance" key="isBalance" label="是否结算" width="80px" align="center">
            <template slot-scope="scope">
              <span>{{i18n.getMsg('financeMgr.balance.'+scope.row.isBalance)}}</span>
            </template>
          </el-table-column>
          <el-table-column column-key="money" key="money" label="结算金额" min-width="100px" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.isBalance==='1'">{{scope.row.money}}</span>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" column-key="payTime" key="payTime" label="预计结算日期" width="110px" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.isBalance!=='1'&&scope.row.payTime!==''">
                {{moment(scope.row.payTime).format('YYYY-MM-DD')}}
              </span>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" prop="inCountTime" key="inCountTime" label="下单时间" width="110px" align="center"></el-table-column>
          <el-table-column :resizable="false" prop="purchaseTime" key="purchaseTime" label="采购时间" width="110px" align="center"></el-table-column>
          <el-table-column :resizable="false" prop="inDay" key="inDay" key="inDay" label="入库日期" width="100px" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.inDay!==''">{{moment(scope.row.inDay).format('YYYY-MM-DD')}}</span>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" prop="balanceTime" key="balanceTime" label="结算时间" width="110px" align="center"></el-table-column>
          <el-table-column prop="createUser" key="createUser" label="制单人" min-width="110px" header-align="center"></el-table-column>
        </el-table>
      </div>
      <table-pagination v-if="pagination.totalCount!==0" :pagination="pagination" @change="pageChange">
      </table-pagination>

      <el-dialog :fullscreen="dialogType!=='detail'" :title="dialogTitle" :visible.sync="openDialog" :top="dialogType==='detail'?'10vh':'0'"
        custom-class="material-dialog" @closed="dialogClosed">
        <div style="overflow:auto" :style="dialogType==='detail'?'height:calc(80vh - 54px)':'100%'">
          <template v-if="openDialog">
            <balance-detail v-if="dialogType==='detail'" :warehouse="selectWarehouse"></balance-detail>
            <payment-form v-else-if="dialogType==='payment'" type="material" :warehouse="selectWarehouse" @pay-success="paySuccess">
              <template slot="table-column">
              <el-table-column :resizable="false" column-key="type" label="入库类型" key="type" width="120px" align="center">
                <template slot-scope="scope">
                  <span>{{i18n.getMsg('financeMgr.type.'+scope.row.warehouse.type)}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="warehouse.purchaseId" key="purchaseId" label="采购单号" min-width="140px" header-align="center">
              </el-table-column>
              <el-table-column prop="warehouse.orderId" key="orderId" label="订单编号" min-width="140px" header-align="center">
              </el-table-column>
              <el-table-column prop="warehouse.factoryNo" key="factoryNo" label="工厂型号" min-width="120px" header-align="center">
              </el-table-column>
              <el-table-column prop="warehouse.coustomId" key="coustomId" label="客户型号" min-width="120px" header-align="center">
              </el-table-column>
              <el-table-column prop="warehouse.providerName" key="providerName" label="供应商" min-width="120px" header-align="center">
              </el-table-column>
              <el-table-column prop="warehouse.materialName" key="materialName" label="物料名称" min-width="120px" header-align="center">
              </el-table-column>
              <el-table-column prop="warehouse.materialType" key="materialType" label="物料类型" min-width="120px" header-align="center">
              </el-table-column>
              <el-table-column prop="warehouse.model" key="model" label="规格型号" min-width="120px" header-align="center">
              </el-table-column>
              <el-table-column prop="warehouse.color" key="color" label="编号" min-width="120px" header-align="center">
              </el-table-column>
              <el-table-column prop="warehouse.colorDescription" key="colorDescription" label="描述" min-width="120px" header-align="center">
              </el-table-column>
              <el-table-column prop="warehouse.materialDeptName" key="materialDeptName" label="物料部门" min-width="120px" align="center">
              </el-table-column>
              <el-table-column prop="warehouse.inCountUnit" key="inCountUnit" label="入库单位" min-width="100px" align="center"></el-table-column>
              <el-table-column prop="warehouse.inCountPrice" key="inCountPrice" label="入库单价" min-width="100px" align="center"></el-table-column>
              <el-table-column prop="warehouse.unitPrice" key="unitPrice" label="采购单价" min-width="100px" align="center"></el-table-column>
              <el-table-column prop="warehouse.count" key="count" label="数量" min-width="100px" align="center"></el-table-column>
              <el-table-column prop="warehouse.totalPrice" key="totalPrice" label="入库金额" min-width="100px" align="center">
              </el-table-column>
              <el-table-column :resizable="false" prop="warehouse.purchaseTime" key="purchaseTime" label="采购时间" width="110px" align="center"></el-table-column>
              <el-table-column prop="warehouse.createUser" key="createUser" label="制单人" min-width="110px" header-align="center"></el-table-column>
              </template>
            </payment-form>
          </template>
        </div>
      </el-dialog>

      <el-dialog fullscreen class="dialog-fullscreen" title="材料应付汇总" :visible.sync="openStat">
        <div style="height:100%;overflow:auto">
          <material-balance-stat v-if="openStat" :search="search" :dropdown-option="dropdownOption" @stat-closed="statClosed">
          </material-balance-stat>
        </div>
      </el-dialog>
    </div>
  `;

  return {
    mixins: [
      tablePaginationMixin(),
      tableColShowMixin('inMaterialBalance')
    ],
    data: function () {
      var search = {
        type: '',
        providerName: '',
        model: '',
        color: '',
        materialName: '',
        materialDept: '',
        isBalance: '',
        orderId: '',
        companyOrderId: '',
        customerNo: '',
        factoryNo: '',
        createUser: '',
        startDate: moment().startOf('month').valueOf(),
        endDate: moment().endOf('month').valueOf(),
        inStartDay: null,
        inEndDay: null,
        startPrice: undefined,
        endPrice: undefined
      };
      return {
        loading: false,
        search: search,
        oldSearch: null,
        warehouseList: [],
        dropdownOption: {},
        statData: null,
        openDialog: false,
        openStat: false,
        dialogTitle: '',
        dialogType: null,
        selectWarehouse: null,
        selectWarehouseList: [],
        user: null,
        handleWidth: '80px',
        moment: moment,
        i18n: i18n
      };
    },

    created: function () {
      var self = this;
      this.loading = true;
      this.setUser().then(function () {
        self.loading = false;
      }).catch(function () {
        self.loading = false;
      });
    },

    methods: {
      setUser: function () {
        var self = this;
        return SysUtil.getUser().then(function (user) {
          var fixedCreateUser = _.get(user, 'userPagePermission.fixedWarehouseCreateUser');

          var search = self.search;
          search.fixedCreateUser = fixedCreateUser;
          if (fixedCreateUser) {
            search.createUser = user.userId;
            self.search = _.cloneDeep(search);
          }

          self.oldSearch = _.cloneDeep(search);
          self.user = user;
          return user;
        });
      },

      setWarehouseList: function (isSearch) {
        if (!isSearch) {
          this.search = _.cloneDeep(this.oldSearch);
        }

        var pagination = this.pagination;
        var currentPage = pagination.currentPage;
        var pageSize = pagination.pageSize;
        var start = (currentPage - 1) * pageSize;

        var postData = {
          start: start,
          length: pageSize
        };
        this.setPostData(postData);

        if (isSearch) {
          postData.isSum = true;
        }

        this.loading = true;
        var self = this;
        ajaxRequest('warehouseInSumMoney/getWarehouseInSumMoneyDetail', postData).then(function (res) {
          if (isSearch) {
            self.oldSearch = _.cloneDeep(self.search);
            var totalMoney = res.sum,
              receiptPaymentPrice = res.receiptPaymentPrice;
            var nonReceiptPaymentPrice = _.round(totalMoney - receiptPaymentPrice, 2);
            if (nonReceiptPaymentPrice < 0) {
              nonReceiptPaymentPrice = 0;
            }

            var monthSum = res.monthSum || 0;
            var monthTeceiptPaymentPrice = res.monthTeceiptPaymentPrice || 0;
            var monthMoney = _.round(monthSum - monthTeceiptPaymentPrice, 2);
            self.statData = {
              totalMoney: totalMoney,
              receiptPaymentPrice: receiptPaymentPrice,
              nonReceiptPaymentPrice: nonReceiptPaymentPrice,
              monthSum: monthSum,
              monthMoney: monthMoney
            };
          }
          var warehouseData = res.list;
          var warehouseList = warehouseData.returnData;
          var hasHandle = false;
          for (var i = 0; i < warehouseList.length; i++) {
            var warehouse = warehouseList[i];
            var totalPrice = warehouse.inOutMoney;
            SysUtil.tableSetDeptData(warehouse);
            if (SysUtil.isEmpty(totalPrice) || totalPrice === 0) {
              var inCountPrice = warehouse.inCountPrice;
              var count = warehouse.count;
              if (inCountPrice !== null || count !== null) {
                totalPrice = _.round(inCountPrice * count, 2);
              }
            }
            warehouse.totalPrice = totalPrice;

            var createTime = warehouse.createTime;
            var estimatedPay = warehouse.estimatedPay;
            var payTime = '';
            if (createTime !== null) {
              if (estimatedPay === null) {
                estimatedPay = 0;
              } else if (typeof estimatedPay === 'string') {
                estimatedPay = Number(estimatedPay);
              }
              payTime = moment(createTime).add(estimatedPay, 'month').valueOf();
            }
            warehouse.payTime = payTime;

            var inDay = warehouse.inDay;
            if (SysUtil.isEmpty(inDay)) {
              warehouse.inDay = '';
            } else {
              warehouse.inDay = moment(inDay).valueOf();
            }

            if (warehouse.isBalance === '0' && !hasHandle) {
              hasHandle = true;
            }
          }

          self.handleWidth = hasHandle ? '130px' : '80px';
          self.warehouseList = warehouseList;
          self.pagination.totalCount = warehouseData.iTotalRecords;
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      setPostData: function (postData) {
        var search = this.search;
        var fields = ['type', 'providerName', 'materialName', 'color', 'model', 'isBalance', 'orderId',
          'companyOrderId', 'customerNo', 'factoryNo', 'createUser', 'startPrice', 'endPrice'
        ];
        SysUtil.setPostData(postData, search, fields);

        var materialDept = search.materialDept;
        if (materialDept !== '') {
          postData.materialDeptId = materialDept.materialDeptId;
        }

        if (search.startDate !== null) {
          postData.startDate = moment(search.startDate).format('YYYY-MM-DD');
        }
        if (search.endDate !== null) {
          postData.endDate = moment(search.endDate).format('YYYY-MM-DD');
        }
        if (search.inStartDay !== null) {
          postData.inStartDay = moment(search.inStartDay).format('YYYY-MM-DD');
        }
        if (search.inEndDay !== null) {
          postData.inEndDay = moment(search.inEndDay).format('YYYY-MM-DD');
        }
      },

      resetSearch: function () {
        this.search = _.cloneDeep(this.oldSearch);
      },

      searchData: function () {
        this.pagination.currentPage = 1;
        this.setWarehouseList(true);
      },

      pageChange: function () {
        this.setWarehouseList();
      },

      checkSelectable: function (warehouse) {
        return warehouse.isBalance === '0';
      },

      selectionChange: function (warehouseList) {
        this.selectWarehouseList = warehouseList;
      },

      lookPaymentRcord: function (warehouse, column) {
        var columnKey = column.columnKey;
        if (columnKey === 'handle') {
          return;
        }

        this.dialogTitle = '收付款记录';
        this.selectWarehouse = warehouse;
        this.dialogType = 'detail';
        this.openDialog = true;
      },

      paymentMoney: function (warehouse) {
        this.dialogTitle = '付款';
        this.selectWarehouse = warehouse;
        this.dialogType = 'payment';
        this.openDialog = true;
      },

      paymentMoneys: function () {
        var warehouseList = this.selectWarehouseList;
        if (warehouseList.length === 0) {
          this.$alert('请选择需要付款的入库单', '信息');
          return;
        }
        var data = _.uniqBy(warehouseList, 'providerName');
        if (data.length !== 1) {
          this.$alert('需要付款的入库单只能有一个供应商');
          return;
        }

        this.dialogTitle = '付款';
        this.selectWarehouse = warehouseList;
        this.dialogType = 'payment';
        this.openDialog = true;
      },

      paySuccess: function () {
        this.openDialog = false;
        this.setWarehouseList();
      },

      dialogClosed: function () {
        this.dialogTitle = '';
        this.dialogType = null;
        this.selectWarehouse = null;
      },

      balanceOrder: function (warehouse) {
        var self = this;
        this.$confirm('确定要结算此入库单吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }).then(function () {
          self.toBalanceOrder(warehouse);
        }).catch(function () {});
      },

      toBalanceOrder: function (warehouse) {
        this.loading = true;
        var self = this;
        ajaxRequest('warehouseInSumMoney/setIsBalanceByWarehouseInSumId', {
          id: warehouse.id,
          isBalance: '1',
          money: warehouse.totalPrice
        }).then(function (res) {
          self.$alert('结算成功', '信息', {
            callback: function () {
              self.setWarehouseList();
            }
          });
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      exportExcel: function () {
        this.search = _.cloneDeep(this.oldSearch);
        var postData = {};
        this.setPostData(postData);
        var formParam = SysUtil.formatFormParam(postData);
        var basePath = SysUtil.getBasePath();
        var path = `${basePath}/warehouseInSumMoney/exportWarehouseInSumMoneyDetail?${formParam}`;
        window.open(path);
      },

      lookStat: function () {
        this.openStat = true;
      },

      statClosed: function (search) {
        if (!SysUtil.equalsObj(this.oldSearch, search)) {
          this.search = _.cloneDeep(search);
          this.oldSearch = _.cloneDeep(search);
          this.searchData();
        }
      }
    },

    components: {
      SearchBtnView: SearchBtnView,
      MaterialSearchForm: MaterialSearchForm,
      BalanceDetail: BalanceDetail,
      PaymentForm: PaymentForm,
      MaterialBalanceStat: MaterialBalanceStat
    },

    template: template
  };
}();
